<template>
	<div class="page">
		<div class="page-header">
			<h1 class="page-title">教材/专著</h1>
			<p class="page-subtitle">在线填报教材/专著信息，上传证明材料</p>
		</div>

		<div style="margin-bottom: 20px;">
			<el-button type="success" @click="exportData">
				<el-icon><Download /></el-icon>
				导出数据
			</el-button>
			<el-button type="primary" style="margin-left: 8px;" @click="openCreate()">
				<el-icon><Plus /></el-icon>
				在线填报
			</el-button>
		</div>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="title" label="书名" min-width="220" show-overflow-tooltip />
				<el-table-column prop="isbn" label="ISBN" min-width="160" show-overflow-tooltip />
				<el-table-column prop="publisher" label="出版社" min-width="160" show-overflow-tooltip />
				<el-table-column prop="publishDate" label="出版日期" width="120" />
				<el-table-column prop="textbookType" label="教材类型" width="120" />
				<el-table-column prop="level" label="级别" width="100" />
				<el-table-column prop="status" label="状态" width="110">
					<template #default="{ row }">
						<el-tag :type="statusTag(row.status)">{{ statusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="300" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-dialog v-model="showDialog" :title="isEdit ? '编辑教材/专著' : '新增教材/专著'" width="780px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
				<el-form-item label="书名" prop="title"><el-input v-model="form.title" /></el-form-item>
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="ISBN" prop="isbn"><el-input v-model="form.isbn" /></el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="出版社" prop="publisher"><el-input v-model="form.publisher" /></el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="出版日期" prop="publish_date">
							<el-date-picker v-model="form.publish_date" type="date" value-format="YYYY-MM-DD" style="width:100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="教材类型" prop="textbook_type">
							<el-select v-model="form.textbook_type" placeholder="请选择" style="width:100%">
								<el-option label="规划教材" value="规划教材" />
								<el-option label="精品教材" value="精品教材" />
								<el-option label="普通教材" value="普通教材" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="16">
					<el-col :span="12"><el-form-item label="级别" prop="level">
						<el-select v-model="form.level" placeholder="请选择" style="width:100%">
							<el-option label="校级" value="校级" />
							<el-option label="省部级" value="省部级" />
							<el-option label="国家级" value="国家级" />
						</el-select>
					</el-form-item></el-col>
					<el-col :span="12"><el-form-item label="再版信息" prop="reprint_info"><el-input v-model="form.reprint_info" /></el-form-item></el-col>
				</el-row>
				<el-row :gutter="16">
					<el-col :span="24">
						<el-form-item label="作者/编者">
							<el-table :data="authors" size="small" style="width:100%">
								<el-table-column label="姓名" width="200">
									<template #default="{ row }"><el-input v-model="row.author_name" placeholder="姓名" /></template>
								</el-table-column>
								<el-table-column label="校内排名" width="140">
									<template #default="{ row }"><el-input v-model.number="row.in_campus_rank" placeholder="数字" /></template>
								</el-table-column>
								<el-table-column label="角色" width="160">
									<template #default="{ row }"><el-input v-model="row.role" placeholder="作者/编者" /></template>
								</el-table-column>
								<el-table-column label="字数(千字)" width="160">
									<template #default="{ row }"><el-input v-model.number="row.word_count" placeholder="可选" /></template>
								</el-table-column>
								<el-table-column label="操作" width="120">
									<template #default="{ $index }"><el-button size="small" type="danger" @click="removeAuthor($index)">删除</el-button></template>
								</el-table-column>
							</el-table>
							<div style="margin-top:8px"><el-button size="small" @click="addAuthor">新增作者/编者</el-button></div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="字数(千字)" prop="word_count"><el-input v-model.number="form.word_count" /></el-form-item>

				<el-form-item v-if="!isEdit" label="证明材料">
					<el-upload
						v-model:file-list="fileList"
						class="upload-demo"
						drag
						:limit="5"
						:before-upload="beforeUpload"
						:auto-upload="false"
						accept=".jpg,.jpeg,.png,.pdf"
					>
						<el-icon class="el-icon--upload"><UploadFilled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>（可选）</div>
						<template #tip><div class="el-upload__tip">支持 JPG/PNG/PDF，单个不超过 20MB，最多 5 个</div></template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">{{ isEdit ? '保存' : '提交' }}</el-button>
			</template>
		</el-dialog>

		<el-dialog v-model="showView" title="查看教材/专著" width="640px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="书名">{{ currentRow?.title }}</el-descriptions-item>
				<el-descriptions-item label="ISBN">{{ currentRow?.isbn }}</el-descriptions-item>
				<el-descriptions-item label="出版社">{{ currentRow?.publisher }}</el-descriptions-item>
				<el-descriptions-item label="出版日期">{{ currentRow?.publishDate }}</el-descriptions-item>
				<el-descriptions-item label="角色">{{ currentRow?.editorRole || '-' }}</el-descriptions-item>
				<el-descriptions-item label="校内排名">{{ currentRow?.inCampusRank || '-' }}</el-descriptions-item>
				<el-descriptions-item label="字数(千字)">{{ currentRow?.wordCount || '-' }}</el-descriptions-item>
				<el-descriptions-item label="类型">{{ currentRow?.textbookType || '-' }}</el-descriptions-item>
				<el-descriptions-item label="级别">{{ currentRow?.level || '-' }}</el-descriptions-item>
				<el-descriptions-item label="再版信息">{{ currentRow?.reprintInfo || '-' }}</el-descriptions-item>
				<el-descriptions-item label="状态">{{ statusText(currentRow?.status) }}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="showView = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus, UploadFilled, Download } from '@element-plus/icons-vue'
import { textbookApi } from '@/api/textbook'
import { ElMessage, ElMessageBox } from 'element-plus'

const showDialog = ref(false)
const isEdit = ref(false)
const showView = ref(false)
const currentRow = ref(null)
const formRef = ref()
const submitting = ref(false)

const form = reactive({
	title: '', isbn: '', publisher: '', publish_date: '', word_count: '', editor_role: '', in_campus_rank: '',
	textbook_type: '', level: '', reprint_info: ''
})

const rules = {
	title: [{ required: true, message: '请输入书名', trigger: 'blur' }]
}

const fileList = ref([])
const tableData = ref([])
const authors = ref([])

const statusTag = (s) => ({ 'PENDING': 'warning', 'APPROVED': 'success', 'REJECTED': 'danger' }[s] || 'info')
const statusText = (s) => ({ 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已驳回' }[s] || s)

const openCreate = () => {
	isEdit.value = false
	Object.assign(form, { title: '', isbn: '', publisher: '', publish_date: '', word_count: '', editor_role: '', in_campus_rank: '', textbook_type: '', level: '', reprint_info: '' })
	fileList.value = []
	authors.value = []
	showDialog.value = true
}

const beforeUpload = (file) => {
	const okType = ['image/jpeg','image/png','application/pdf']
	const ok = okType.includes(file.type) && file.size <= 20 * 1024 * 1024
	if (!ok) ElMessage.error('请上传 JPG/PNG/PDF 且不超过20MB')
	return ok
}

const loadTable = async () => {
	try {
		const res = await textbookApi.listMine()
		const arr = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		tableData.value = arr.map(r => ({
			...r,
			publishDate: r.publishDate ?? r.publish_date,
			textbookType: r.textbookType ?? r.textbook_type,
			reprintInfo: r.reprintInfo ?? r.reprint_info,
			editorRole: r.editorRole ?? r.editor_role,
			inCampusRank: r.inCampusRank ?? r.in_campus_rank,
			wordCount: r.wordCount ?? r.word_count
		}))
	} catch (e) { console.error(e) }
}

const handleSubmit = async () => {
	try {
		if (!formRef.value) return
		await formRef.value.validate()
		submitting.value = true
		if (!isEdit.value) {
			const res = await textbookApi.create({
				title: form.title,
				isbn: form.isbn || null,
				publisher: form.publisher || null,
				publish_date: form.publish_date || null,
				word_count: form.word_count || null,
				editor_role: form.editor_role || null,
				in_campus_rank: form.in_campus_rank || null,
				textbook_type: form.textbook_type || null,
				level: form.level || null,
				reprint_info: form.reprint_info || null,
				authors: authors.value
			})
			const id = res?.id || res?.data?.id
			if (fileList.value.length > 0 && id) {
				for (const f of fileList.value) {
					await textbookApi.uploadAttachment(id, f.raw || f)
				}
			}
			ElMessage.success('提交成功，等待审核')
		} else {
			await textbookApi.update(currentRow.value.id, {
				title: form.title,
				isbn: form.isbn || null,
				publisher: form.publisher || null,
				publish_date: form.publish_date || null,
				word_count: form.word_count || null,
				editor_role: form.editor_role || null,
				in_campus_rank: form.in_campus_rank || null,
				textbook_type: form.textbook_type || null,
				level: form.level || null,
				reprint_info: form.reprint_info || null,
				authors: authors.value
			})
			ElMessage.success('保存成功')
		}
		showDialog.value = false
		await loadTable()
	} catch (e) {
		console.error(e)
		ElMessage.error(e?.response?.data?.message || e?.message || '提交失败')
	} finally { submitting.value = false }
}

const handleView = (row) => { currentRow.value = row; showView.value = true }

const handleEdit = (row) => {
	currentRow.value = row
	isEdit.value = true
	Object.assign(form, {
		title: row.title,
		isbn: row.isbn || '',
		publisher: row.publisher || '',
		publish_date: row.publishDate || '',
		word_count: row.wordCount || '',
		editor_role: row.editorRole || '',
		in_campus_rank: row.inCampusRank || '',
		textbook_type: row.textbookType || '',
		level: row.level || '',
		reprint_info: row.reprintInfo || ''
	})
	// 加载作者
	loadAuthors(row.id)
	showDialog.value = true
}

const addAuthor = () => {
	authors.value.push({ author_name: '', in_campus_rank: null, role: '', word_count: null })
}
const removeAuthor = (idx) => {
	authors.value.splice(idx, 1)
}
const loadAuthors = async (id) => {
	try {
		const res = await textbookApi.listAuthors(id)
		authors.value = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		// 统一字段命名
		authors.value = authors.value.map(a => ({
			author_name: a.author_name ?? a.authorName,
			in_campus_rank: a.in_campus_rank ?? a.inCampusRank,
			role: a.role,
			word_count: a.word_count ?? a.wordCount
		}))
	} catch {}
}

const handleDelete = async (row) => {
	try {
		await ElMessageBox.confirm('确定删除该记录吗？', '删除确认', { type: 'warning' })
		await textbookApi.remove(row.id)
		ElMessage.success('删除成功')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') ElMessage.error(e?.response?.data || e?.message || '删除失败')
	}
}

const exportData = async () => {
	const { exportData: exportUtil } = await import('@/utils/exportUtils')
	
	const filters = {}
	
	await exportUtil('textbooks', filters, '教材编写列表.xlsx')
}

loadTable()
</script>

<style scoped>
.page { }
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
.upload-demo { width: 100%; }
</style> 